package com.dkd.service.impl;

import com.alibaba.fastjson.JSON;
import com.dkd.exception.LogicException;
import com.dkd.service.ESOrderService;
import com.dkd.vo.OrderVO;
import com.dkd.vo.Pager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * impl esorder服务
 *
 * @author DiXiaoNie
 * @date 2023/02/07
 * @since 2023/2/7 12:00
 */
@Service
@Slf4j
public class ESOrderServiceImpl implements ESOrderService {

    @Autowired
    private RestHighLevelClient esClient;

    /**
     * 搜索
     *
     * @param pageIndex 页面索引
     * @param pageSize  页面大小
     * @param orderNo   订单Id
     * @param openId    开放id
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return {@link Pager }<{@link OrderVO }>
     * @author DiXiaoNie
     * @date 2023/02/07
     */
    @Override
    public Pager<OrderVO> search(Integer pageIndex, Integer pageSize, String orderNo, String openId, String startDate, String endDate) {
        SearchRequest searchRequest = new SearchRequest("order");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //根据订单号查询
        if (StringUtils.isNotBlank(orderNo)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("order_no", orderNo));
        }
        //根据openId查询
        if (StringUtils.isNotBlank(openId)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("open_id", openId));
        }
        //根据时间范围查询
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("update_time");
            rangeQueryBuilder.gte(startDate);
            rangeQueryBuilder.lte(endDate);
            boolQueryBuilder.must(rangeQueryBuilder);
        }
        //按照最后更新时间由近到远的排序规则排序
        sourceBuilder.from((pageIndex - 1) * pageSize);
        sourceBuilder.size(pageSize);

        sourceBuilder.sort("update_time", SortOrder.DESC);
        //如果条数大于10000 显示实际条数
        sourceBuilder.trackTotalHits(true);
        sourceBuilder.query(boolQueryBuilder);
        searchRequest.source(sourceBuilder);

        //开始请求并处理响应
        try {
            SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);

            //获取所有命中的订单并转换为订单VO对象
            List<OrderVO> orderVOList = new ArrayList<>();
            SearchHits hits = response.getHits();
            hits.forEach(hit -> {
                String orderStr = hit.getSourceAsString();
                OrderVO orderVO = JSON.parseObject(orderStr, OrderVO.class);
                orderVOList.add(orderVO);
            });
            //新建分页对象并返回
            Pager<OrderVO> pager = new Pager<>();
            pager.setPageIndex(pageIndex);
            pager.setPageSize(pageSize);
            pager.setTotalCount(hits.getTotalHits().value);
            pager.setCurrentPageRecords(orderVOList);

            return pager;

        } catch (Exception e) {
            e.printStackTrace();
            log.error("搜索出错");
            throw new LogicException("搜素出错");
        }
    }
}
